﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using System;
using System.Web.UI.WebControls;
using NeoPatterns.Core.Registry;
using NeoPatterns.Utility;

namespace NeoPatterns.Patterns.IoC
{
    /// <summary>
    /// Dependency injected version of ObjectDataSource
    /// </summary>
    public class ObjectDataSource : System.Web.UI.WebControls.ObjectDataSource
    {
        public ObjectDataSource()
        {
            ObjectCreating += InjectDependency;
        }

        /// <summary>
        /// Tries to inject the object, instead of creating one.
        /// The method is "soft": it doesn't break if nothing is found
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InjectDependency(object sender, ObjectDataSourceEventArgs e)
        {
            // lookup for the real type
            var type = TypeLoader.GetType(TypeName);
            // then tries to find if anyone matches: the type itself or the implemented interfaces
            foreach (var baseType in type.GetBaseTypes(BaseType.Type | BaseType.Interfaces))
            {
                var names = Application.ObjectRegistry.GetNamesForType(baseType);
                if (names.Count == 1)
                {
                    e.ObjectInstance = Application.ObjectRegistry.Get(names[0]);
                    break;
                }
            }
        }
    }
}
